$().ready(function(){
    if ($("#albumId").val() != "") {
        var albumphoto = $("#albumphoto").val();
        $("input[@type=radio][value='" + albumphoto + "']").attr("checked", true);
        $(".main_photo").attr("src", albumphoto);
    }
    var uploader = '../js-plugin/uploadify/uploadify_cn.swf';
    var images_script = "/action/master/AlbumImageUpload";
    var cancelImg = '../js-plugin/uploadify/cancel.png';
    var folder = '/upload';
    var identifies = {
        'identifies': $("#identifies").val()
    };
    
    $('#images_file').uploadify({
        'uploader': uploader,
        'script': images_script,
        'cancelImg': cancelImg,
        'scriptData': identifies,//解决firefox 的session bug
        'folder': folder,
        'auto': true,
        'multi': true,
        'width': 110,
        'fileExt': '*.jpg;*.gif;*.png;*.bmp',
        'fileDesc': '请选择图片文件 (.JPG, .GIF, .PNG, .BMP)',
        'queueID': 'custom-queue',
        'buttonText': "选择上传图片",
        'removeCompleted': true,
        'onComplete': function(e, queueId, fileObj, response, data){
            var obj = $.parseJSON(response);
            if (obj.success) {
                var templateTr = $("#photo-preview-tpl").children("li").clone().show();
                templateTr.find("img").attr("src", obj.filepath);
                templateTr.find("a").attr("href", obj.fileid);
                templateTr.find("a").click(delphotoClickHandler).easyconfirm({
                    locale: {
                        title: '操作确认',
                        text: '您确定要删除该这张图片么？',
                        button: ['取消', '是的，确定删除']
                    }
                });
                templateTr.find("input").val(obj.filepath);
                templateTr.find(".setphoto").click(setPhoto);
                $('#photo-preview').append(templateTr);
                $(".loadingbox").empty();
                $(".loadingbox").append(loadingTpl, {
                    icoType: "succ",
                    loadIcon: "",
                    msgHtml: fileObj.name + " 上传成功"
                });
                $(".loadingbox").fadeIn(50);
                $(".loadingbox").delay(2000).fadeOut(600);
            }
            else {
                $(".loadingbox").empty();
                $(".loadingbox").append(loadingTpl, {
                    icoType: 'fail',
                    loadIcon: '',
                    msgHtml: obj.message
                });
                $(".loadingbox").delay(3000).fadeOut(600);
                $('#status-message').append("<li>" + obj.message + "</li>");
            }
        }
    });
    
    var delphotoClickHandler = function(e){
        var tmp = $(e.currentTarget);
        var tmpid = tmp.attr("href");
        $.post("/action/master/deleteAlbumPhoto", {
            Action: "post",
            id: tmpid
        }, function(data, textStatus){
            if (!data.success) {
                //$("#attachment_msg").text("删除图片时出现问题，请将错误信息发送给管理员处理："+data.message);
                //$(".attachmentMSG").removeClass("success").addClass("error").fadeTo("slow", 1).fadeIn(400).delay(4000).slideUp(400);
                $(".loadingbox").empty();
                $(".loadingbox").append(loadingTpl, {
                    icoType: 'fail',
                    loadIcon: '',
                    msgHtml: "删除图片时出现问题，请将错误信息发送给管理员处理：" + data.message
                });
                $(".loadingbox").delay(3000).fadeOut(600);
            }
            else {
                //$("#attachment_msg").text("图片删除成功！");
                // $(".attachmentMSG").removeClass("error").addClass("success").fadeTo("slow", 1).fadeIn(400).delay(4000).slideUp(400);
                $(".loadingbox").empty();
                $(".loadingbox").append(loadingTpl, {
                    icoType: "succ",
                    loadIcon: "",
                    msgHtml: "图片删除成功！"
                });
                $(".loadingbox").fadeIn(50);
                $(".loadingbox").delay(2000).fadeOut(600);
                tmp.parents("li").hide(2000, function(){
                    tmp.parents("li").remove();
                });
                if (tmp.parents("li").find(".setphoto").is(':checked')) {
                    $(".main_photo").attr("src", "/images/manage/blank.gif");
                }
            }
        }, "json");
    };
    $(".delphoto").click(delphotoClickHandler).easyconfirm({
        locale: {
            title: '操作确认',
            text: '您确定要删除该这张图片么？',
            button: ['取消', '是的，确定删除']
        }
    });
    
    var setPhoto = function(e){
        $(".main_photo").attr("src", $(e.currentTarget).val());
    };
    $(".setphoto").click(setPhoto);
    
    
    $(".resetFrom").click(function(){
        $("#albumEditor").resetForm();
        $('#photo-preview').text("");
        $('#id').val("");
        $(".main_photo").attr("src", "/images/manage/blank.gif");
        return false;
    });
    
    $(".saveBtn").click(function(){
        $("#albumEditor").submit();
        return false;
    });
    
    // 中文字两个字节       
    jQuery.validator.addMethod("byteRangeLength", function(value, element, param){
        var length = value.length;
        for (var i = 0; i < value.length; i++) {
            if (value.charCodeAt(i) > 127) {
                length++;
            }
        }
        return this.optional(element) || (length >= param[0] && length <= param[1]);
    }, "请确保输入的值在3-15个字节之间(一个中文字算2个字节)");
    
    $("#albumEditor").validate({
        submitHandler: function(form){
            var tmpMainphoto = "";
            if ($("input[name='photo']:checked").val() !== undefined) {
                tmpMainphoto = $("input[name='photo']:checked").val();
            }
            else {
                $("#errormsg").text("请设定图集封面");
                $(".post-state").removeClass("success").addClass("error").fadeTo("slow", 1).fadeIn(400).delay(4000).slideUp(400);
                return false;
            };
            $(form).ajaxSubmit({
                target: "#errormsg",
                data: {
                    photo: tmpMainphoto
                },
                dataType: "json",
                beforeSubmit: function(){
                    $(".loadingbox").append(loadingTpl, {
                        icoType: 'clear',
                        loadIcon: '<img src=\"/images/manage/loading002.gif\">',
                        msgHtml: '正在提交数据，请稍候...'
                    });
                    $(".loading").fadeIn(50);
                },
                success: function(data){
                    if (!data.success) {
                        //$("#errormsg").text(data.message);
                        //$(".post-state").removeClass("success").addClass("error").fadeTo("slow", 1).fadeIn(400).delay(4000).slideUp(400);
                        $(".loadingbox").empty();
                        $(".loadingbox").append(loadingTpl, {
                            icoType: 'fail',
                            loadIcon: '',
                            msgHtml: data.message
                        });
                        $(".loadingbox").delay(3000).fadeOut(600);
                    }
                    else {
                        //$("#errormsg").text(data.message);
                        //$(".post-state").removeClass("error").addClass("success").fadeTo("slow", 1).fadeIn(400).delay(4000).slideUp(400);
                        $(".loadingbox").empty();
                        $(".loadingbox").append(loadingTpl, {
                            icoType: "succ",
                            loadIcon: "",
                            msgHtml: data.message
                        });
                        $(".loadingbox").fadeIn(50);
                        $(".loadingbox").delay(2000).fadeOut(600);
                    }
                }
            });
        },
        rules: {
            title: {
                required: true,
                byteRangeLength: [4, 200]
            },
            content: {
                required: true,
                byteRangeLength: [4, 500]
            }
        },
        messages: {
            title: {
                required: "请填写图集名称",
                byteRangeLength: "图集名称必须在4-200个字符之间(一个中文字算2个字符)"
            },
            content: {
                required: "请填写图集说明",
                byteRangeLength: "图集说明必须在4-500个字符之间(一个中文字算2个字符)"
            }
        }
    });
    
});
